/*
 *
 * @Author: Jevon
 * @Date: 2021-12-19 21:00:47
 */
const VuiClipboardCommon = (function() {
  function createFakeElement(value) {
    const isRTL = document.documentElement.getAttribute('dir') === 'rtl';
    const fakeElement = document.createElement('textarea');
    // Prevent zooming on iOS
    fakeElement.style.fontSize = '12pt';
    // Reset box model
    fakeElement.style.border = '0';
    fakeElement.style.padding = '0';
    fakeElement.style.margin = '0';
    // Move element out of screen horizontally
    fakeElement.style.position = 'absolute';
    fakeElement.style[isRTL ? 'right' : 'left'] = '-9999px';
    // Move element to the same position vertically
    const yPosition = window.pageYOffset || document.documentElement.scrollTop;
    fakeElement.style.top = `${yPosition}px`;

    fakeElement.setAttribute('readonly', '');
    fakeElement.value = value;

    return fakeElement;
  }

  function command(type) {
    try {
      return document.execCommand(type);
    } catch (err) {
      return false;
    }
  }

  function select(element) {
    let selectedText;

    if (element.nodeName === 'SELECT') {
      element.focus();

      selectedText = element.value;
    } else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
      const isReadOnly = element.hasAttribute('readonly');

      if (!isReadOnly) {
        element.setAttribute('readonly', '');
      }

      element.select();
      element.setSelectionRange(0, element.value.length);

      if (!isReadOnly) {
        element.removeAttribute('readonly');
      }

      selectedText = element.value;
    } else {
      if (element.hasAttribute('contenteditable')) {
        element.focus();
      }

      const selection = window.getSelection();
      const range = document.createRange();

      range.selectNodeContents(element);
      selection.removeAllRanges();
      selection.addRange(range);

      selectedText = selection.toString();
    }

    return selectedText;
  }

  /**
   * 触发剪切板事件
   * @param {*} cmd
   * @param {*} func
   * @return {*}
   */
  function triggerClipboard(cmd, func) {
    const fakeElement = createFakeElement('');
    document.body.appendChild(fakeElement);

    const handle = evt => {
      func(evt);
      evt.preventDefault();
    };
    fakeElement.addEventListener(cmd, handle);
    command(cmd);
    fakeElement.removeEventListener(cmd, handle);
    fakeElement.remove();
  }

  return {
    createFakeElement,
    command,
    select,
    triggerClipboard
  };
})();
export default VuiClipboardCommon;
